package com.qqt.csr.archive.assembler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.qqt.csr.archive.entity.reader.*;
import com.qqt.csr.archive.entity.writer.ArchiveConversation;
import com.qqt.csr.archive.enums.ConversationType;
import com.qqt.csr.archive.response.ArchiveConversationResponse;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: yang hao
 * @Date: 2024/11/20 15:25
 * @Description: 归档会话 装配器
 **/
@Slf4j
public class ConversationArchiveAssembler {

    /**
     * 归档会话 填充人工会话数据
     * @param conversation {@link ArchiveConversation} 归档会话实体
     * @param artificialConversation {@link ArtificialConversation} 人工会话实体
     */
    public static void fill(ArchiveConversation conversation, ArtificialConversation artificialConversation) {
        // 若人工会话为空，则抛出异常
        Optional.ofNullable(artificialConversation).orElseThrow(() -> new IllegalArgumentException("artificialConversation cannot be null"));
        // 填充会话数据
        conversation.setConversationId(artificialConversation.getId());
        conversation.setConversationType(ConversationType.ARTIFICIAL.name());
        conversation.setConversationStartTime(artificialConversation.getStartTime());
        conversation.setConversationEndTime(artificialConversation.getEndTime());
        conversation.setRoomId(artificialConversation.getRoomId());
        conversation.setSensitiveWordMsgCount(artificialConversation.getSensitiveWordMsgCount());
    }

    /**
     * 归档会话 填充渠道数据
     * @param conversation {@link ArchiveConversation} 归档会话实体
     * @param channel {@link ImH5Manage} 渠道数据
     */
    public static void fill(ArchiveConversation conversation, ImH5Manage channel) {
        // 若渠道为空，则返回
        if (channel == null) {
            return;
        }
        // 填充渠道数据
        conversation.setChannelId(channel.getChannelId().toString());
        conversation.setChannelName(channel.getChannelName());
        conversation.setChannelService(channel.getChannelBusiness());
        //默认H5, 无法定位数据逻辑
        conversation.setChannelType("H5");
    }

    /**
     * 归档会话 填充人工会话扩展字段
     * @param conversation {@link ArchiveConversation} 归档会话实体
     * @param ext {@link String} 人工客服扩展字段
     */
    public static void fill(ArchiveConversation conversation, String ext) {
        // 若扩展字段为空或JSON格式不合法，则返回
        if (ext == null || !JSONUtil.isTypeJSON(ext)) {
            return;
        }
        // 填充技能组数据
        String skillSetId = JSONUtil.parseObj(ext).getStr("skillSetId", null);
        conversation.setSkillSetId(skillSetId);
        String skillSetName = JSONUtil.parseObj(ext).getStr("skillSetName", null);
        conversation.setSkillSetName(skillSetName);
    }

    /**
     * 归档会话 填充访客账户
     * @param conversation {@link ArchiveConversation} 归档会话实体
     * @param userAccount {@link CsrImAccount} 访客账户实体
     */
    public static void fill(ArchiveConversation conversation, CsrImAccount userAccount) {
        // 若访客账户为空，则返回
        if (userAccount == null) {
            return;
        }
        // 填充访客数据
        if (Objects.nonNull(userAccount.getExt())) {
            conversation.setUserId(userAccount.getExt().getUId());
        }
        conversation.setUserName(userAccount.getAccountName());
        conversation.setUserAccountId(userAccount.getId().toString());
    }

    /**
     * 归档会话 填充客服账户数据
     * @param conversation {@link ArchiveConversation} 归档会话
     * @param csAccount {@link CsrImAccount} 客服账户
     * @param sysUser {@link SysUser} 客服信息
     */
    public static void fill(ArchiveConversation conversation, CsrImAccount csAccount, SysUser sysUser) {
        // 若客服账户为空，则返回
        if (csAccount != null) {
            conversation.setCsAccountId(csAccount.getId().toString());
        }
        // 若客服信息为空，则返回
        if (sysUser != null) {
            conversation.setCsId(sysUser.getUserId().toString());
            conversation.setCsName(sysUser.getNickName());
            conversation.setCsDeptId(sysUser.getDeptId().toString());
            conversation.setCsDept(sysUser.getDeptName());
            conversation.setCsJobNumber(sysUser.getJobId());
        }
    }

    /**
     * 填充会话 机器人账户
     * @param conversation {@link ArchiveConversation} 归档会话
     * @param robotAccount {@link CsrImAccount} 访客账户
     */
    public static void fillRobot(ArchiveConversation conversation, CsrImAccount robotAccount) {
        // 若机器人账户为空，则返回
        if (robotAccount == null) {
            return;
        }
        // 填充机器人数据
        if (Objects.nonNull(robotAccount.getExt())) {
            conversation.setCsId(robotAccount.getExt().getCsId());
        }
        conversation.setCsName(robotAccount.getAccountName());
        conversation.setCsAccountId(robotAccount.getId().toString());
    }

    /**
     * 整理会话
     * @param conversation {@link ArchiveConversation} 归档会话
     * @param artificialConversation {@link ArtificialConversation} 人工会话
     */
    public static void tidyUp(ArchiveConversation conversation, ArtificialConversation artificialConversation) {
        // 若人工会话为空，则抛出异常
        Optional.ofNullable(artificialConversation).orElseThrow(() -> new IllegalArgumentException("artificialConversation cannot be null"));
        // 填充人工会话扩展字段
        String initiatorId = artificialConversation.getInitiatorId();
        String ext = artificialConversation.getExt();
        Map<String, Object> artificialExt = new HashMap<>();
        artificialExt.put("initiatorId", initiatorId);
        artificialExt.put("ext", ext);
        conversation.setArtificialExt(JSONUtil.toJsonStr(artificialExt));
    }

    /**
     * 填充会话 智能客服
     * @param conversation {@link ArchiveConversation} 归档会话
     * @param smartConversation {@link SmartConversation} 智能客服会话
     */
    public static void fill(ArchiveConversation conversation, SmartConversation smartConversation) {
        // 若智能客服会话为空，则抛出异常
        Optional.ofNullable(smartConversation).orElseThrow(() -> new IllegalArgumentException("smartConversation cannot be null"));
        // 填充会话信息
        conversation.setUserId(smartConversation.getVisitorId());
        conversation.setUserName(smartConversation.getVisitorName());
        conversation.setConversationId(smartConversation.getId());
        conversation.setConversationType(ConversationType.SMART.name());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        conversation.setConversationStartTime(sdf.format(smartConversation.getSessionStartTime()));
        conversation.setConversationEndTime(sdf.format(smartConversation.getSessionEndTime()));
        conversation.setChannelId(smartConversation.getChannelId().toString());
        conversation.setChannelType(smartConversation.getChannelType());
        conversation.setChannelName(smartConversation.getChannelName());
        conversation.setChannelService(smartConversation.getChannelBusiness());
        // 智能客服会话 技能组为空
        // 智能客服会话 客服id与name填充为机器人id与name
        conversation.setCsId(smartConversation.getRebotId().toString());
        conversation.setCsName(smartConversation.getRebotName());
        // 访客与机器人账号id于writer时查询是否存在，若不存在则创建填充
    }

    /**
     * 整理会话
     * @param conversation {@link ArchiveConversation} 归档会话
     * @param smartConversation {@link SmartConversation} 智能客服会话
     */
    public static void tidyUp(ArchiveConversation conversation, SmartConversation smartConversation) {
        // 若智能客服会话为空，则抛出异常
        Optional.ofNullable(smartConversation).orElseThrow(() -> new IllegalArgumentException("smartConversation cannot be null"));
        // 填充智能客服会话扩展字段
        String sessionRisk = smartConversation.getSessionRisk();
        Integer isLeaveMsg = smartConversation.getIsLeaveMsg();
        String sessionIntention = smartConversation.getSessionIntention();
        Integer isTransferAgent = smartConversation.getIsTransferAgent();
        Map<String, Object> smartExt = Maps.newHashMap();
        smartExt.put("sessionRisk", sessionRisk);
        smartExt.put("isLeaveMsg", isLeaveMsg);
        smartExt.put("sessionIntention", sessionIntention);
        smartExt.put("isTransferAgent", isTransferAgent);
        conversation.setSmartExt(JSONUtil.toJsonStr(smartExt));
    }

    /**
     * 归档会话集合 转换为 归档会话响应集合
     * @param conversations {@link List<ArchiveConversation>} 归档会话集合
     * @return {@link List<ArchiveConversationResponse>} 归档会话响应集合
     */
    public static List<ArchiveConversationResponse> convert(List<ArchiveConversation> conversations) {
        if (conversations == null || conversations.isEmpty()) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(conversations, ArchiveConversationResponse.class);
    }

    /**
     * 归档会话 转换为 归档会话响应
     * @param conversation {@link ArchiveConversation} 归档会话
     * @return {@link ArchiveConversationResponse} 归档会话响应
     */
    public static ArchiveConversationResponse convert(ArchiveConversation conversation) {
        return BeanUtil.copyProperties(conversation, ArchiveConversationResponse.class);
    }

}
